<template>
  <div class="delivery-system">
    <div class="header">
      <h1>配送记录管理</h1>
      <div class="filter-controls">
        <el-select v-model="filterStatus" placeholder="订单状态" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="待配送" value="待配送"></el-option>
          <el-option label="配送中" value="配送中"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
          <el-option label="已取消" value="已取消"></el-option>
        </el-select>

        <el-select v-model="filterMethod" placeholder="取餐方式" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="配送" value="配送"></el-option>
          <el-option label="堂食" value="堂食"></el-option>
        </el-select>

        <el-date-picker
            v-model="filterDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />

        <el-button type="primary" @click="searchOrders">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>
    </div>

    <div class="order-list">
      <div
          class="order-card"
          v-for="order in filteredOrders"
          :key="order.id"
          :class="{
          'status-pending': order.status === '待配送',
          'status-delivering': order.status === '配送中',
          'status-completed': order.status === '已完成',
          'status-cancelled': order.status === '已取消'
        }"
      >
        <div class="order-header">
          <div class="order-id">订单编号：{{ order.id }}</div>
          <div class="order-status">
            <el-tag
                :type="getStatusTagType(order.status)"
                size="small"
            >
              {{ order.status }}
            </el-tag>
          </div>
        </div>

        <div class="order-dishes">
          <div class="dishes-title">菜品：</div>
          <div class="dishes-list">
            <span v-for="(dish, index) in order.dishes" :key="index">
              {{ dish.name }}*{{ dish.quantity }}<span v-if="index < order.dishes.length - 1">、</span>
            </span>
          </div>
        </div>

        <div class="order-info">
          <div class="info-item">
            <span>菜品数量：</span>
            <span>{{ order.totalQuantity }}</span>
          </div>
          <div class="info-item">
            <span>取餐方式：</span>
            <span>{{ order.method }}</span>
            <span v-if="order.method === '配送'" class="delivery-address">
              （{{ order.address }}）
            </span>
          </div>
          <div class="info-item">
            <span>支付方式：</span>
            <span>{{ order.payment }}</span>
          </div>
        </div>

        <div class="order-payment">
          <div class="payment-item">
            <span>订单金额：</span>
            <span>￥{{ order.totalPrice.toFixed(2) }}</span>
          </div>
          <div class="payment-item">
            <span>折扣金额：</span>
            <span>￥{{ order.discount.toFixed(2) }}</span>
          </div>
          <div class="payment-item">
            <span>实付金额：</span>
            <span class="actual-price">￥{{ order.actualPrice.toFixed(2) }}</span>
          </div>
          <div class="payment-item">
            <span>下单时间：</span>
            <span>{{ order.orderTime }}</span>
          </div>
        </div>

        <div class="order-remark" v-if="order.remark">
          <span>订单备注：</span>
          <span>{{ order.remark }}</span>
        </div>

        <div class="order-actions">
          <el-button
              v-if="order.status === '待配送'"
              size="small"
              type="primary"
              @click="startDelivery(order)"
          >
            开始配送
          </el-button>
          <el-button
              v-if="order.status === '配送中'"
              size="small"
              type="success"
              @click="completeDelivery(order)"
          >
            完成配送
          </el-button>
          <el-button
              v-if="order.status === '待配送' || order.status === '配送中'"
              size="small"
              type="danger"
              @click="cancelOrder(order)"
          >
            取消订单
          </el-button>
          <el-button
              size="small"
              @click="viewOrderDetail(order)"
          >
            查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="`订单详情 - ${currentOrder?.id}`" width="50%">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusTagType(currentOrder.status)">
              {{ currentOrder.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ currentOrder.orderTime }}</el-descriptions-item>
          <el-descriptions-item label="取餐方式">{{ currentOrder.method }}</el-descriptions-item>
          <el-descriptions-item label="配送地址" v-if="currentOrder.method === '配送'">
            {{ currentOrder.address }}
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ currentOrder.payment }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">￥{{ currentOrder.totalPrice.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="折扣金额">￥{{ currentOrder.discount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="实付金额">
            <span class="actual-price">￥{{ currentOrder.actualPrice.toFixed(2) }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <h3>菜品清单</h3>
        <el-table :data="currentOrder.dishes" border style="width: 100%">
          <el-table-column prop="name" label="菜品名称"></el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="scope">
              ￥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="scope">
              ￥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-remark" v-if="currentOrder.remark">
          <h3>订单备注</h3>
          <p>{{ currentOrder.remark }}</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  setup() {
    // 订单数据
    const orders = ref([
      {
        id: 'DD20180606175013',
        status: '配送中',
        dishes: [
          { name: '玉米炖排骨', quantity: 1, price: 30 },
          { name: '川香辣子鸡', quantity: 1, price: 40 },
          { name: '紫菜蛋花汤', quantity: 1, price: 20 }
        ],
        totalQuantity: 3,
        method: '配送',
        address: '康复一区1102号60床号',
        payment: '微信扫码支付',
        totalPrice: 90,
        discount: 0,
        actualPrice: 90,
        orderTime: '2018-06-06 15:20:30',
        remark: '少放辣椒'
      },
      {
        id: 'DD20180606175014',
        status: '配送中',
        dishes: [
          { name: '玉米炖排骨', quantity: 1, price: 30 },
          { name: '川香辣子鸡', quantity: 1, price: 40 },
          { name: '紫菜蛋花汤', quantity: 1, price: 20 }
        ],
        totalQuantity: 3,
        method: '堂食',
        payment: '微信扫码支付',
        totalPrice: 90,
        discount: 0,
        actualPrice: 90,
        orderTime: '2018-06-06 15:20:30',
        remark: '少放辣椒'
      },
      {
        id: 'DD20180606175015',
        status: '待配送',
        dishes: [
          { name: '玉米炖排骨', quantity: 1, price: 30 },
          { name: '川香辣子鸡', quantity: 1, price: 40 },
          { name: '紫菜蛋花汤', quantity: 1, price: 20 }
        ],
        totalQuantity: 3,
        method: '堂食',
        payment: '微信扫码支付',
        totalPrice: 90,
        discount: 0,
        actualPrice: 90,
        orderTime: '2018-06-06 15:20:30',
        remark: '少放辣椒'
      },
      {
        id: 'DD20180606175016',
        status: '已完成',
        dishes: [
          { name: '红烧肉', quantity: 2, price: 35 },
          { name: '清炒时蔬', quantity: 1, price: 18 }
        ],
        totalQuantity: 3,
        method: '配送',
        address: '康复二区805号32床号',
        payment: '支付宝支付',
        totalPrice: 88,
        discount: 10,
        actualPrice: 78,
        orderTime: '2018-06-05 11:30:15',
        remark: '红烧肉要肥一点的'
      },
      {
        id: 'DD20180606175017',
        status: '已取消',
        dishes: [
          { name: '清蒸鱼', quantity: 1, price: 45 },
          { name: '米饭', quantity: 2, price: 2 }
        ],
        totalQuantity: 3,
        method: '堂食',
        payment: '现金支付',
        totalPrice: 49,
        discount: 0,
        actualPrice: 49,
        orderTime: '2018-06-04 18:45:22',
        remark: '不要放葱'
      }
    ])

    // 筛选条件
    const filterStatus = ref('')
    const filterMethod = ref('')
    const filterDate = ref([])

    // 当前查看的订单
    const currentOrder = ref(null)
    const detailDialogVisible = ref(false)

    // 根据状态获取标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case '待配送': return 'warning'
        case '配送中': return 'primary'
        case '已完成': return 'success'
        case '已取消': return 'danger'
        default: return 'info'
      }
    }

    // 过滤后的订单
    const filteredOrders = computed(() => {
      let result = [...orders.value]

      // 按状态筛选
      if (filterStatus.value) {
        result = result.filter(order => order.status === filterStatus.value)
      }

      // 按取餐方式筛选
      if (filterMethod.value) {
        result = result.filter(order => order.method === filterMethod.value)
      }

      // 按日期筛选
      if (filterDate.value && filterDate.value.length === 2) {
        const startDate = new Date(filterDate.value[0])
        const endDate = new Date(filterDate.value[1])

        result = result.filter(order => {
          const orderDate = new Date(order.orderTime)
          return orderDate >= startDate && orderDate <= endDate
        })
      }

      return result
    })

    // 搜索订单
    const searchOrders = () => {
      // 过滤逻辑已经在 computed 属性中处理
      ElMessage.success('筛选条件已应用')
    }

    // 重置筛选条件
    const resetFilters = () => {
      filterStatus.value = ''
      filterMethod.value = ''
      filterDate.value = []
      ElMessage.success('筛选条件已重置')
    }

    // 开始配送
    const startDelivery = (order) => {
      ElMessageBox.confirm('确定要开始配送此订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        order.status = '配送中'
        ElMessage.success('订单状态已更新为"配送中"')
      }).catch(() => {
        // 取消操作
      })
    }

    // 完成配送
    const completeDelivery = (order) => {
      ElMessageBox.confirm('确定此订单已完成配送吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        order.status = '已完成'
        ElMessage.success('订单状态已更新为"已完成"')
      }).catch(() => {
        // 取消操作
      })
    }

    // 取消订单
    const cancelOrder = (order) => {
      ElMessageBox.confirm('确定要取消此订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        order.status = '已取消'
        ElMessage.success('订单已取消')
      }).catch(() => {
        // 取消操作
      })
    }

    // 查看订单详情
    const viewOrderDetail = (order) => {
      currentOrder.value = order
      detailDialogVisible.value = true
    }

    return {
      orders,
      filterStatus,
      filterMethod,
      filterDate,
      filteredOrders,
      currentOrder,
      detailDialogVisible,
      getStatusTagType,
      searchOrders,
      resetFilters,
      startDelivery,
      completeDelivery,
      cancelOrder,
      viewOrderDetail
    }
  }
}
</script>

<style scoped>
.delivery-system {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  margin-bottom: 15px;
}

.filter-controls {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.order-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
}

.order-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.order-card.status-pending {
  border-left: 4px solid #e6a23c;
}

.order-card.status-delivering {
  border-left: 4px solid #409eff;
}

.order-card.status-completed {
  border-left: 4px solid #67c23a;
}

.order-card.status-cancelled {
  border-left: 4px solid #f56c6c;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.order-id {
  font-weight: bold;
  font-size: 16px;
}

.order-status {
  margin-left: 10px;
}

.order-dishes {
  display: flex;
  margin-bottom: 15px;
}

.dishes-title {
  font-weight: bold;
  margin-right: 5px;
}

.dishes-list {
  flex: 1;
}

.order-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.delivery-address {
  color: #666;
  margin-left: 5px;
}

.order-payment {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-bottom: 15px;
}

.payment-item {
  display: flex;
  align-items: center;
}

.actual-price {
  color: #f56c6c;
  font-weight: bold;
}

.order-remark {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.order-remark span:first-child {
  font-weight: bold;
  margin-right: 5px;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 订单详情样式 */
.order-detail {
  padding: 10px;
}

.order-detail h3 {
  margin: 20px 0 10px;
  color: #333;
}

.order-remark p {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 5px;
}
</style>